﻿/* Copyright (c) 2010 EPiServer AB
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
 * to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace EPiServer.Municipality.Web.UI.WebControls {
    /// <summary>
    /// Summary description for PagingControl.
    /// </summary>
    /// <remarks>
    /// </remarks>
    public class PagingControl : WebControl {

        /* *******************************************************************
        *  Properties 
        * *******************************************************************/
        #region public PagedDataSource Source
        /// <summary>
        /// Get/Sets the Source of the PagingControl
        /// </summary>
        /// <value></value>
        public PagedDataSource Source {
            get {
                return _source;
            }
            set {
                _source = value;
            }
        }
        private PagedDataSource _source;
        #endregion
        #region private int CurrentPageIndex
        /// <summary>
        /// Gets the CurrentPageIndex of the NewsList
        /// </summary>
        /// <value></value>
        private int CurrentPageIndex {
            get {
                if (HttpContext.Current.Request.QueryString["page"] != null) {
                    int index = (Convert.ToInt32(HttpContext.Current.Request.QueryString["page"]) - 1);
                    // correct for a page index less than 0 or greater then last page
                    if (index < 0)
                        index = 0;
                    if (index > Source.PageCount)
                        index = (Source.PageCount - 1);
                    return index;
                }
                return 0;
            }
        }
        #endregion
        #region public string ResultText
        /// <summary>
        /// Get/Sets the ResultText of the PagingControl
        /// </summary>
        /// <value></value>
        public string ResultText {
            get { return _resultText; }
            set { _resultText = value; }
        }
        private string _resultText;
        #endregion

        /* *******************************************************************
        *  Constructors
        * *******************************************************************/
        #region public PagingControl(PagedDataSource source)
        /// <summary>
        /// Initializes a new instance of the <b>PagingControl</b> class.
        /// </summary>
        /// <param name="source"></param>
        public PagingControl(PagedDataSource source) {
            _source = source;
        }
        #endregion

        /* *******************************************************************
        *  Methods 
        * *******************************************************************/
        #region protected override void CreateChildControls()
        /// <summary>
        /// 
        /// </summary>
        protected override void CreateChildControls() {
            // Abort if not data
            if (Source.PageCount < 2) {
                Visible = false;
                return;
            }

            HyperLink hyperLink;
            HtmlGenericControl control;
            if (!Source.IsFirstPage) {
                hyperLink = new HyperLink {
                                              NavigateUrl = UriSupport.AddQueryString(
                                                  HttpContext.Current.Request.Url.PathAndQuery, "page", ((Source.CurrentPageIndex + 1) - 1).ToString()),
                                              Text = "< Föregående",
                                              CssClass = "prev"
                                          };
                Controls.Add(hyperLink);
            } else {
                control = new HtmlGenericControl("span") { InnerText = "< Föregående" };
                control.Attributes.Add("class", "atstart");
                Controls.Add(control);
            }
            // Show three pages before current
            int startPosition = CurrentPageIndex - 3;
            if (startPosition < 0)
                startPosition = 0;

            // show 7 pages in paginator
            int lastPosition = startPosition + 7;
            if (lastPosition > Source.PageCount) {
                lastPosition = Source.PageCount;
                startPosition = (Source.PageCount < 7) ? 0 : (Source.PageCount - 7);
            }

            if ((startPosition + 1) > 1) {
                control = new HtmlGenericControl("span") { InnerText = "..." };
                control.Attributes.Add("class", "break");
                Controls.Add(control);
            }

            for (int i = (startPosition + 1); i < (lastPosition + 1); i++) {
                if ((CurrentPageIndex + 1) == i) {
                    control = new HtmlGenericControl("span") { InnerText = i.ToString() };
                    control.Attributes.Add("class", "current");
                    Controls.Add(control);
                } else {
                    hyperLink = new HyperLink {
                                                  NavigateUrl = UriSupport.AddQueryString(
                                                      HttpContext.Current.Request.Url.PathAndQuery, "page", i.ToString()),
                                                  Text = i.ToString()
                                              };
                    Controls.Add(hyperLink);
                }
            }

            if ((CurrentPageIndex + 4) < Source.PageCount) {
                control = new HtmlGenericControl("span") { InnerText = "..." };
                control.Attributes.Add("class", "break");
                Controls.Add(control);
            }

            if (!Source.IsLastPage) {
                hyperLink = new HyperLink {
                                              NavigateUrl = UriSupport.AddQueryString(
                                                  HttpContext.Current.Request.Url.PathAndQuery, "page", ((Source.CurrentPageIndex + 1) + 1).ToString()),
                                              Text = "Nästa >",
                                              CssClass = "next"
                                          };
                Controls.Add(hyperLink);
            } else {
                control = new HtmlGenericControl("span") { InnerText = "Nästa >" };
                control.Attributes.Add("class", "atend");
                Controls.Add(control);
            }
        }
        #endregion
        #region public override void RenderBeginTag(HtmlTextWriter writer)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="writer"></param>
        public override void RenderBeginTag(HtmlTextWriter writer) {
            writer.Write("<div class=\"paginator\">");
            writer.Write("<div>");
        }
        #endregion
        #region public override void RenderEndTag(HtmlTextWriter writer)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="writer"></param>
        public override void RenderEndTag(HtmlTextWriter writer) {
            writer.Write("</div>");
            writer.Write("<div class=\"results\">");
            writer.Write("(" + Source.DataSourceCount + " " + ResultText + ")");
            writer.Write("</div>");
            writer.Write("</div>");
        }
        #endregion
    }
}